package top.kaoshanji.p1ch08a;

import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

/**
 * 代码清单-p1ch08a-153页a：PerfStatListener类
 * @author kaoshanji
 * ^_^
 * create time 2025/4/8 10:44
 */
@WebListener
public class PerfStatListener implements ServletRequestListener {

    // ServletRequest 属性名
    private final static String SERVLET_REQUEST_ATTRIBUTE_START_TIME = "start.time";

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        ServletRequest servletRequest = sre.getServletRequest();
        servletRequest.setAttribute(SERVLET_REQUEST_ATTRIBUTE_START_TIME, System.nanoTime());
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        ServletRequest servletRequest = sre.getServletRequest();

        Long start = (Long)servletRequest.getAttribute(SERVLET_REQUEST_ATTRIBUTE_START_TIME);
        Long end = System.nanoTime();

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        String uri = httpServletRequest.getRequestURI();
        System.out.println("time taken to execute " + uri + " : " + ((end - start) / 1000) + " microseconds");

    }

}
